package com.example.moneygrosService;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

import android.app.Dialog;
import android.app.ListActivity;
import android.content.AsyncQueryHandler;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.database.ContentObserver;
import android.database.Cursor;
import android.os.Bundle;
import android.os.Handler;
import android.provider.BaseColumns;
import android.util.Log;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CursorAdapter;
import android.widget.ListView;
import android.widget.NumberPicker;
import android.widget.TextView;
import android.widget.Toast;

import com.example.moneygrosService.database.MoneyContract;
import com.example.moneygrosService.database.MoneyContract.Users;
import com.example.moneygrosService.handlers.DeleteContactHandler;
import com.example.moneygrosService.handlers.ModifyBalanceHandler;
import com.example.moneygrosService.handlers.ResultListener;


public class MainActivityService extends ListActivity {
	private static final String TAG = MainActivityService.class.getSimpleName();

	MainActivityServiceUserContentObserver mContentObserver;

	private CursorAdapter mAdapter;

	final Context context = this ;

	interface REQUEST_CODES {
		int ADD_CONTACT=1;
		int MODIFY_USER_PROFILE=2;
		int SERVICE_MODIFY_USER_PROFILE=3;
		int SERVICE_CHECK_USER_PROFILE=4;
	};

	public interface DB_TOKEN {
		int CHECK_USER_FOR_INSERT=10;
		int INSERT_USER=11;

		int CHECK_USER_FOR_UPDATE=20;
		int UPDATE_USER=21;

		int CHECK_USER_FOR_DELETE=25;
		int DELETE_USER=25;

		int CHECK_USER_FOR_BALANCE_UPDATE=30;
		int UPDATE_BALANCE=31;

		int CHECK_USER_UPDATE_USER_PROFILE = 40;
		int UPDATE_USER_PROFILE = 41;
		int INSERT_USER_PROFILE = 42;
		int CHECK_USER_PROFILE_FOR_ACTIVITY = 49;

		int CHECK_BALANCE=4;
		int INSERT_BALANCE=5;
		//    	int UPDATE_BALANCE=6;    	
	};

	@Override
	public void onCreate(Bundle savedInstanceState) {
		Log.d(TAG, "onCreate");
		
		super.onCreate(savedInstanceState);

		mContentObserver = new MainActivityServiceUserContentObserver(null, this);
		getContentResolver().registerContentObserver(MoneyContract.BASE_CONTENT_URI, true, mContentObserver);

		startService(new Intent(this, DatabaseService.class));
		startService(new Intent(this, CommunicationManagerService.class));

		setContentView(R.layout.activity_main);
		ListView lv = getListView();
		registerForContextMenu(lv);        
		lv.setClickable(true);

		lv.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

				long _ID = ((ListView) parent).getItemIdAtPosition(position);
				Log.v("onItemClick", "clicked. ID :"+ _ID);
				// custom dialog
				final Dialog dialog = new Dialog(context);
				dialog.setTitle(R.string.money_dialog_title);
				dialog.setContentView(R.layout.money_dialog_layout);

				TextView IDTextView= (TextView) dialog.findViewById(R.id.money__ID);
				Log.v("onItemClick", "clicked. heowesme:"+ IDTextView);
				IDTextView.setText(String.valueOf(_ID));


				NumberPicker balance = (NumberPicker) dialog.findViewById(R.id.numberPicker1);
				balance.setWrapSelectorWheel(false);
				balance.setMinValue(0);
				balance.setMaxValue(99);
				balance.setValue(0);

				balance = (NumberPicker) dialog.findViewById(R.id.numberPicker2);
				balance.setWrapSelectorWheel(false);
				balance.setMinValue(0);
				balance.setMaxValue(99);
				balance.setValue(0);

				Button dialogButton = (Button) dialog.findViewById(R.id.button1);
				dialogButton.setOnClickListener(new OnClickListener() {
					@Override
					public void onClick(View v) {
						// l'utilisateur a rempli sa requète.
						// Faire les tests qui s'imposent et agir en fonction
						Request request=new Request();
						request.setInitiator(true);
 
						SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); 
						Date date = new Date();
						request.setDate(dateFormat.format(date));
 
						TextView IDTextView= (TextView) dialog.findViewById(R.id.money__ID);
						long _ID = Long.valueOf(IDTextView.getText().toString());
						request.setRequest_ID_row(_ID);

						//        				Toast.makeText(context, "user id "+_ID, Toast.LENGTH_SHORT).show();
						CheckBox IOweCheckBox = (CheckBox) dialog.findViewById(R.id.money_I_owe);
						request.setI_owe(IOweCheckBox.isChecked());

						double offset =0;
						NumberPicker balance= (NumberPicker) dialog.findViewById(R.id.numberPicker1);
						offset += (balance.getValue())*100;

						balance= (NumberPicker) dialog.findViewById(R.id.numberPicker2);

						offset += balance.getValue();
						if (request.isI_owe()){
							request.setOffset(-offset);
						} else {
							request.setOffset(offset);                			
						}

						Log.v("onclick", "offset "+ request.getOffset());

						ModifyBalanceHandler modifyBalanceHandler = new ModifyBalanceHandler(getContentResolver());
						modifyBalanceHandler.modifyBalance(request);


						dialog.dismiss();
					}
				});

				dialog.show(); 
			}
		});


		
		mAdapter = new ListItemCursorAdapter(this,  null);
		setListAdapter(mAdapter);

	      // Partie test
			 ((Button) findViewById(R.id.buttonShowCustomDialog)).setOnClickListener(new OnClickListener() {
	 
				@Override
				public void onClick(View arg0) {

//					User user = new User("remi.laplace@gmail.com"+Integer.toString(balance_test), "Rémi",Integer.toString(balance_test), "1.0", 0, false);
//					checkAndInsertUser(user);
	//
	                Intent intent = new Intent(getApplicationContext(), AddContact.class);
	   				startActivityForResult(intent, REQUEST_CODES.ADD_CONTACT);

			  }
			});
			 ((Button) findViewById(R.id.buttonPublish)).setOnClickListener(new OnClickListener() {
				 
				@Override
				public void onClick(View arg0) {

//					User user = new User("remi.laplace@gmail.com"+Integer.toString(balance_test), "Rémi",Integer.toString(balance_test), "1.0", 0, false);
//					checkAndInsertUser(user);
	//
	                Intent intent = new Intent(getApplicationContext(), PublishBT.class);
	   				startActivity(intent);

			  }
			});
		updateList();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.activity_main, menu);
		return true;
	}

	@Override
	public void onCreateContextMenu(ContextMenu menu, View v,
			ContextMenuInfo menuInfo) {
		super.onCreateContextMenu(menu, v, menuInfo);
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.list_users_context_menu, menu);
	}

	/* (non-Javadoc)
	 * @see android.app.Activity#onContextItemSelected(android.view.MenuItem)
	 */
	@Override
	public boolean onContextItemSelected(MenuItem item) {
		AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
		switch (item.getItemId()) {
		case R.id.list_users_context_menu_edit_user:
			//			editNote(info.id);

			return true;
		case R.id.list_users_context_menu_del_user:
			//			deleteNote(info.id);
			//			CheckAndDeleteUser(info.)
			Toast.makeText(this, "user id "+getListView().getItemIdAtPosition(info.position), Toast.LENGTH_SHORT).show();

			long expectedToBeID=getListView().getItemIdAtPosition(info.position);

			DeleteContactHandler deleteContactHandler = new DeleteContactHandler(getContentResolver(), MoneyContract.Users.buildUri(String.valueOf(expectedToBeID)));
			deleteContactHandler.delUser();
			//			mNotifiyingAsyncQueryHandler.startDelete(MoneyContract.Users.buildUri(String.valueOf(expectedToBeID)));

			return true;
		default:
			return super.onContextItemSelected(item);
		}
	}
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// Handle item selection
		switch (item.getItemId()) {
		case R.id.menu_add_user:
			startUserListActivity();
			return true;
		case R.id.menu_modify_profile:
			startUserProfileActivity();
			return true;
		case R.id.menu_settings:

			return true;
		default:
			return super.onOptionsItemSelected(item);
		}
	}

	private void startUserListActivity() {
		Intent intent = new Intent(getApplicationContext(), AddContact.class);
		startActivityForResult(intent, REQUEST_CODES.ADD_CONTACT);
	}
	private void startUserProfileActivity() {
		Intent intent = new Intent(getApplicationContext(), UserProfileActivity.class);
		startActivityForResult(intent, REQUEST_CODES.MODIFY_USER_PROFILE);
	}

	public void updateList() {
		Log.v(TAG, "updateList");

		final MainActivityService mAct = this;
		runOnUiThread(new Runnable(){
			public void run(){
				UpdateGUIUserListHandler updateGUIUserListHandler = new UpdateGUIUserListHandler(getContentResolver(), mAct);		
				updateGUIUserListHandler.updateList();
			}
		});
	}

	private class MainActivityServiceContentObserver extends ContentObserver{
		protected MainActivityService mAct;

		public MainActivityServiceContentObserver(Handler handler) {
			super(handler);
			// TODO Auto-generated constructor stub
		}
		public MainActivityServiceContentObserver(Handler handler, MainActivityService act) {
			super(handler);
			// TODO Auto-generated constructor stub
			mAct = act;
		}		
	}

	private class MainActivityServiceUserContentObserver extends MainActivityServiceContentObserver {
		public MainActivityServiceUserContentObserver(Handler handler, MainActivityService act) {
			super(handler, act);
			// TODO Auto-generated constructor stub
		}

		/* (non-Javadoc)
		 * @see android.database.ContentObserver#onChange(boolean)
		 */
		@Override
		public void onChange(boolean selfChange) {
			Log.v(TAG, "CHECK_BALANCE");
			updateList();
		}		
	}



	class ListItemCursorAdapter extends CursorAdapter {
		public ListItemCursorAdapter(Context context, Cursor c) {
			super(context, c);
		}

		@Override
		public void bindView(View view, Context context, Cursor cursor) {
			TextView userid= (TextView)view.findViewById(R.id.list_user_item_userid);
			userid.setText(cursor.getString(cursor.getColumnIndex(MoneyContract.UsersColumns.USER_ID)));

			TextView username= (TextView)view.findViewById(R.id.list_user_item_username);
			username.setText(cursor.getString(cursor.getColumnIndex(MoneyContract.UsersColumns.USER_NAME)));

			TextView balance= (TextView)view.findViewById(R.id.list_item_current_balance);
			balance.setText(String.valueOf(cursor.getDouble(cursor.getColumnIndex(MoneyContract.UsersColumns.BALANCE ))/100));
		}

		@Override
		public View newView(Context context, Cursor cursor, ViewGroup parent) {
			LayoutInflater inflater = LayoutInflater.from(context);
			View v = inflater.inflate(R.layout.list_user_layout, parent, false);
			bindView(v, context, cursor);
			return v;
		}
	}


	public class UpdateGUIUserListHandler extends AsyncQueryHandler implements Runnable {
		private Bundle mBundle;
		private MainActivityService mAct;
		private ContentResolver mCr;

		private boolean mUserInserted=false;
		private boolean mResult;

		private final Lock mLock = new ReentrantLock();
		private Condition mResultOKCond = mLock.newCondition();
		private boolean mResultOK;

		private ResultListener mListener;

		public UpdateGUIUserListHandler(ContentResolver cr, MainActivityService act) {
			super(cr);
			// TODO Auto-generated constructor stub
			mCr = cr;
			mAct = act;
		}

		public void updateList(){
			String[] projection = {BaseColumns._ID, 
					MoneyContract.UsersColumns.USER_ID, 
					MoneyContract.UsersColumns.USER_NAME, 
					MoneyContract.UsersColumns.BALANCE};
			//		super.startQuery(DB_TOKEN.CHECK_BALANCE,Users.CONTENT_URI, projection);
			startQuery(DB_TOKEN.CHECK_BALANCE, null, Users.CONTENT_URI, projection, null, null, null);
		}

		//		protected void userInserted(boolean insert){
		//			mResultOK = true;
		//			mResult = insert;
		//			mUserInserted = insert;
		//			mListener.onResult(insert, ResultType.USER_INSERTED, null);
		//		}
		/* (non-Javadoc)
		 * @see android.content.AsyncQueryHandler#onQueryComplete(int, java.lang.Object, android.database.Cursor)
		 */
		@Override
		protected void onQueryComplete(int token, Object cookie, Cursor cursor) {
			// TODO Auto-generated method stub
			switch(token){
			case DB_TOKEN.CHECK_BALANCE:
				Log.v("UpdateGUIUserListHandler", "CHECK_BALANCE");
				mAdapter.changeCursor(cursor);
				//    		mAdapter.changeCursor(cursor);
				break;
			}
		}

		@Override
		public void run() {
			// TODO Auto-generated method stub
			//			updateList();
		}
	}
}
